import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  Badge,
  Divider,
  Radio,
  Dropdown,
  Menu,
  Popconfirm,
  Icon,
  Collapse,
  InputNumber,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {nameMaxLength,nameMinLength,remarkMaxLength,regLength} from '@/utils/rule'
import styles from '../search.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const { Panel } = Collapse;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');

const matchTypeValue = ['关键字', '正则表达式'];
const statusMap = ['success', 'error'];
const status = ['启用', '停用'];
const formLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const viewLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addFn,
    updateFn,
    handleModalVisible,
    text,
    form: { getFieldValue },
  } = props;

  const keywordMinLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val > getFieldValue('maxLength')) {
      callback('应小于最大长度');
    }   
    callback();
  };

  const keywordMaxLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val < getFieldValue('minLength'))  {
      callback('应大于最小长度');
    }    
    callback();
  };

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addFn(fieldsValue);
      }
    });
  };

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑敏感字段' : '新增敏感字段'}     
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <div className={styles.modalScroll} style={{paddingRight:16}}>            
      <Collapse defaultActiveKey={['1']} bordered={false} style={{backgroundColor:'#fff'}}>
        <Panel header="基础信息" key="1">
        <FormItem {...formLayout} label="字段名称">
          {form.getFieldDecorator('name', {
            rules: [
              {required: true,whitespace:true,message:'字段名称不能为空'},
              {min:nameMinLength()[0],message:nameMinLength()[1]},
            {max:nameMaxLength()[0],message:nameMaxLength()[1]},           
          ],         
          initialValue: text &&text.name || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>
          <FormItem {...formLayout} label="备注">
            {form.getFieldDecorator('remark',
            {rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],
            initialValue: text &&text.remark || '',
          }
            )(<TextArea
              style={{minHeight: 32}}
              rows={2}
            />)}
          </FormItem>

          {text&&(
             <FormItem {...formLayout} label="状态">
            {form.getFieldDecorator('status', 
            {initialValue:text &&text.status})(
              <Radio.Group>
                <Radio value={0}>
                  启用
                </Radio>
                <Radio value={1}>
                  停用
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
          )}
        </Panel>   
        <Panel header="长度特征" key="2">
          <FormItem {...formLayout} label="固定长度">
          {form.getFieldDecorator('length', {
            initialValue: text &&text.length || '',
          })(<Input placeholder="多个可用英文逗号隔开，如11,13"/>)}
        </FormItem>

            <Form layout="inline">
            <FormItem labelCol={{ span: 11 }} wrapperCol={{ span: 12 }} label="长度范围">
            {form.getFieldDecorator('minLength', {
                    rules: [                    
                      { validator: keywordMinLength },                 
                    ],
                    initialValue: (text &&text.minLength) || '',
                  })(<InputNumber min={0} style={{ width: 120 }} />)}
                </FormItem>
                <FormItem style={{ width: '20px', textAlign: 'right' }}>-</FormItem>
                <FormItem>
                  {form.getFieldDecorator('maxLength', {
                    rules: [                     
                      { validator: keywordMaxLength },                 
                    ],
                    initialValue: (text &&text.maxLength) || '',
                  })(<InputNumber min={1} style={{ width: 120 }} />)}
                </FormItem>
          </Form>
        </Panel>

        <Panel header="字段特征" key="3">
          <FormItem {...formLayout} label="字段名包含">
          {form.getFieldDecorator('columnNameIn', {           
          initialValue: (text &&text.columnNameIn) || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem {...formLayout} label="字段名排除">
          {form.getFieldDecorator('columnNameEx', {          
          initialValue: (text &&text.columnNameEx) || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem {...formLayout} label="备注包含">
          {form.getFieldDecorator('columnRemarkIn', {                 
          initialValue: (text &&text.columnRemarkIn) || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem {...formLayout} label="备注排除">
          {form.getFieldDecorator('columnRemarkEx', {               
          initialValue: text &&text.columnRemarkEx || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>
        </Panel>

        <Panel header="内容特征" key="4">
          <FormItem {...formLayout} label="内容枚举">
          {form.getFieldDecorator('contentEnum', {           
          initialValue: text &&text.contentEnum || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem {...formLayout} label="内容结尾">
          {form.getFieldDecorator('contentEnd', {          
          initialValue: (text &&text.contentEnd) || '',
          })(<Input placeholder="请输入"/>)}
        </FormItem>
        </Panel>

        <Panel header="正则表达式" key="5" style={{borderBottom:'none'}}>   
            {/* <FormItem {...formLayout} label="匹配类型">
            {form.getFieldDecorator('matchType', {
              rules: [{required: true,message:'请选择匹配类型'}],initialValue:"0"
            })(
              <Radio.Group>
                <Radio value="0">
                  关键字
                </Radio>
                <Radio value="1">
                  正则表达式
                </Radio>
              </Radio.Group>
            )}
          </FormItem> */}

        <FormItem {...formLayout} label="正则表达式">
          {form.getFieldDecorator('sensitiveContent', {
            rules: [            
              {max:regLength()[0],message:regLength()[1]},              
            ],
            initialValue: text &&text.sensitiveContent || '',
          })(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>        
          <FormItem {...formLayout} label="扩展正则1">
          {form.getFieldDecorator('sensitiveRex1',
          {initialValue: text &&text.sensitiveRex1 || ''})(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>

        <FormItem {...formLayout} label="扩展正则2">
          {form.getFieldDecorator('sensitiveRex2',
          {initialValue: text &&text.sensitiveRex2 || ''})(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>

        <FormItem {...formLayout} label="扩展正则3">
          {form.getFieldDecorator('sensitiveRex3',
          {initialValue: text &&text.sensitiveRex3 || ''}
          )(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>

        <FormItem {...formLayout} label="扩展正则4">
          {form.getFieldDecorator('sensitiveRex4',          
          {initialValue: text &&text.sensitiveRex4 || ''}
          )(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>
        <FormItem {...formLayout} label="扩展正则5">
          {form.getFieldDecorator('sensitiveRex5',
          {initialValue: text &&text.sensitiveRex5 || ''}
          )(<TextArea
            style={{minHeight: 32}}
            placeholder="请输入"
            rows={3}
          />)}
        </FormItem>
        </Panel>
      </Collapse>     
    </div>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ keyword, loading }) => ({
  keyword,
  loading: loading.models.keyword,
}))
@Form.create()
class keyword extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };


  columns = [
    {
      title: '敏感字段名称',
      dataIndex: 'name',
    },
    {
      title: '固定长度',
      dataIndex: 'length',     
    },
    {
      title: '长度范围',
      render: (text) => (
        <Fragment>
         {text.minLength} - {text.maxLength}
        </Fragment>
      ), 
    },
    {
      title: '正则表达式',
      dataIndex: 'sensitiveContent',
      width:'40%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },

    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      width:140,
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, record)}>详情</a>          
          <Divider type="vertical" />
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.wordId)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();
  }

  
  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  handleThisRowDelete = (wordId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'keyword/remove',
      payload: {wordId},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'keyword/queryList',});
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

//批量删除
  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.wordId;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


      // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {      
      name: data && data.name,      
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'keyword/queryList',  
      payload: values,             
    });    
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询  
      this.pageList(fieldsValue);
    });
  };   

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      editFormValues: record || {},
    });
  };

  handleDetailModalVisible = (flag,text) => {
    this.setState({
      detailModalVisible: !!flag,
      detailsData: text,
    });
  };


// 增加接口
addFn = (fields) => {
  const { dispatch } = this.props;
  const params = {
    name: fields.name,
    sensitiveContent: fields.sensitiveContent,   
    remark: fields.remark,
    columnNameIn:fields.columnNameIn,
    columnNameEx:fields.columnNameEx,
    columnRemarkIn:fields.columnRemarkIn,
    columnRemarkEx:fields.columnRemarkEx,
    contentEnum:fields.contentEnum,
    contentEnd:fields.contentEnd,
    length:fields.length,
    minLength:fields.minLength,
    maxLength:fields.maxLength,
    sensitiveContent: fields.sensitiveContent,
    sensitiveRex1:fields.sensitiveRex1, 
    sensitiveRex2:fields.sensitiveRex2,
    sensitiveRex3:fields.sensitiveRex3,
    sensitiveRex4:fields.sensitiveRex4,
    sensitiveRex5:fields.sensitiveRex5,
  }
  dispatch({
    type: 'keyword/add',
    payload: params,
    callback: (res) => {
      if (res.result == "ok") {
        Modal.success({ title: res.msg });
        this.pageList();
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    },
  });
  this.handleModalVisible();
};


// 更新接口
updateFn = (fields, text) => {
  const { dispatch } = this.props;
  const params = {
    wordId: text.wordId,
    name: fields.name, 
    remark: fields.remark,
    status: fields.status,   
    columnNameIn:fields.columnNameIn,
    columnNameEx:fields.columnNameEx,
    columnRemarkIn:fields.columnRemarkIn,
    columnRemarkEx:fields.columnRemarkEx,
    contentEnum:fields.contentEnum,
    contentEnd:fields.contentEnd,
    length:fields.length,
    minLength:fields.minLength,
    maxLength:fields.maxLength,
    sensitiveContent: fields.sensitiveContent,
    sensitiveRex1:fields.sensitiveRex1, 
    sensitiveRex2:fields.sensitiveRex2,
    sensitiveRex3:fields.sensitiveRex3,
    sensitiveRex4:fields.sensitiveRex4,
    sensitiveRex5:fields.sensitiveRex5,
  }
  dispatch({
    type: 'keyword/update',
    payload: params,
    callback: (res) => {
      if (res.result == "ok") {
        Modal.success({ title: res.msg });
        this.pageList();
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    },
  });
  this.handleModalVisible();
};

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="敏感字段名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
              </Button> 
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      keyword: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, text, editFormValues,detailModalVisible, detailsData } = this.state;

   const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addFn: this.addFn,
      updateFn: this.updateFn
    };  
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    return (
      <PageHeaderWrapper title="敏感字段">
      <Card bordered={false}>       
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.wordId}
          />
        </div>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        {detailsData&&detailsData.wordId?(
          <Details {...detailsMethods} detailModalVisible={detailModalVisible} detailsData={detailsData} />
        ):null}


      </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible,detailsData } = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
    <Row>
      <Col md={12}>
        <FormItem {...viewLayout} label="字段名称">
          {detailsData.name}
        </FormItem>
      </Col>
      <Col md={12}>
        <FormItem {...viewLayout} label="备注">
          {detailsData.remark}
        </FormItem>
      </Col>

      <Col md={12}>
        <FormItem {...viewLayout} label="固定长度">
          {detailsData.length}
        </FormItem>
      </Col>
      <Col md={12}>
        <FormItem {...viewLayout} label="长度范围">
          {detailsData.minLength} ~ {detailsData.maxLength}
        </FormItem>
      </Col>

      <Col md={12}>
        <FormItem {...viewLayout} label="字段名包含">
          {detailsData.columnNameIn}
        </FormItem>
      </Col>
      <Col md={12}>
        <FormItem {...viewLayout} label="字段名排除">
          {detailsData.columnNameEx}
        </FormItem>
      </Col>

      <Col md={12}>
        <FormItem {...viewLayout} label="备注包含">
          {detailsData.columnRemarkIn}
        </FormItem>
      </Col>
      <Col md={12}>
        <FormItem {...viewLayout} label="备注排除">
          {detailsData.columnRemarkEx}
        </FormItem>
      </Col>

      <Col md={12}>
        <FormItem {...viewLayout} label="内容枚举">
          {detailsData.contentEnum}
        </FormItem>
      </Col>
      <Col md={12}>
        <FormItem {...viewLayout} label="内容结尾">
          {detailsData.contentEnd}
        </FormItem>
      </Col>

      {/* <Col md={24}>
        <FormItem id="matchType" {...formLayout} label="匹配类型">
          {matchTypeValue[detailsData.matchType]}
        </FormItem>
      </Col> */}

      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="正则表达式">
          {detailsData.sensitiveContent}
        </FormItem>
      </Col>

      {detailsData.sensitiveRex1&&
      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="扩展正则1">
          {detailsData.sensitiveRex1}
        </FormItem>
      </Col>} 

      {detailsData.sensitiveRex2&&
      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="扩展正则2">
          {detailsData.sensitiveRex2}
        </FormItem>
      </Col>} 

      {detailsData.sensitiveRex3&&
      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="扩展正则3">
          {detailsData.sensitiveRex3}
        </FormItem>
      </Col>} 

      {detailsData.sensitiveRex4&&
      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="扩展正则4">
          {detailsData.sensitiveRex4}
        </FormItem>
      </Col>} 

      {detailsData.sensitiveRex5&&
      <Col md={24}>
        <FormItem labelCol={{span:3}} wrapperCol={{span:21}} label="扩展正则5">
          {detailsData.sensitiveRex5}
        </FormItem>
      </Col>} 
     
    </Row>

      </Modal>
    );
  }
}

export default keyword;
